package Day11;

import java.util.concurrent.locks.ReentrantReadWriteLock;

//测试读写锁
public class TestReadWrite {
    Object data;//数据
    ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();
    public void readData(){
        try {
            rwlock.readLock().lock();
            String name = Thread.currentThread().getName();
            //读取数据
            System.out.println(name+"开始读取2s数据:"+data);
            Thread.sleep(2000);
            System.out.println(name+"结束读取2s数据:"+data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rwlock.readLock().unlock();
        }
    }
    public void writeData(Object data){
        try {
            rwlock.writeLock().lock();
            String name = Thread.currentThread().getName();
            //写入数据
            System.out.println(name+"开始写入2s数据:"+data);
            Thread.sleep(2000);
            this.data = data;
            System.out.println(name+"结束写入2s数据:"+data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rwlock.writeLock().unlock();
        }
    }

    public static void main(String[] args) {
        TestReadWrite trw = new TestReadWrite();
        for (int i = 0; i < 3; i++) {
            new Thread(()->{
                for (int j = 0; j < 5; j++) {
                    trw.readData();
                }
            },"读取"+i).start();
            new Thread(()->{
                for (int j = 0; j < 5; j++) {
                    trw.writeData(System.currentTimeMillis());
                }
            },"写入"+i).start();
        }
    }
}
